package org.hismig.cfg.partition;

import java.util.List;

import org.hismig.cfg.DBConnection;
import org.hismig.migration.Context;
import org.hismig.partition.IDynamicPartition;
import org.hismig.utils.StringTool;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @declare: //TODO <br />
 *           This class created by Vansion.Hopihit on 2012-9-4 <br />
 *           <a href="mailto:vansionhopihit@gmail.com">Contact Me</a>
 * @version 1.0
 * @author Vansion.Hopihit
 * 
 */
public class ConfigurationHelper {

	private static Logger logger = LoggerFactory
			.getLogger(ConfigurationHelper.class);

	public static DBConnection getDBConnection(String dbName, Context context) {
		List<DBConnection> dbConnections;

		// Check cfg file exists
		logger.debug(String.format(
				"Start to check the database[:%s] cfg file if exists", dbName));
		if (Configuration.checkCfgFile(dbName)) {

			logger.info(String.format("The database[:%s] cfg file is exists",
					dbName));

			dbConnections = Configuration.getShardDBConnections(dbName);

			return getDBConnection(dbName, dbConnections, context);
		}
		return null;
	}
	public static DBConnection getDBConnection(String dbName,
			List<DBConnection> dbConnections, Context context) {

		// Match selections
		for (DBConnection dbConnection : dbConnections) {
			String condition = dbConnection
					.getParamByName(IDynamicPartition.KEY_SELECTION);

			logger.debug(String.format(
					"Start to match the database[:%s] selection[:%s]",
					new Object[]{dbName, condition}));

			if (StringTool.evaluate(condition, context.getVariableMap())) {
				// Can match
				logger.info(String
						.format("Match ths selection[:%s]", condition));

				return dbConnection;
			}
		}

		logger.info(String.format(
				"Can't match the database[:%s] any selections",
				new Object[]{dbName}));
		return null;
	}

}
